
#pragma once

#include "zen_vap.h"
#include "MyConfig.h"
#include "RootScene2d.h"
#include "RootScene3d.h"

using namespace Zen;
using namespace Zen::Vap;

class MainDelegate : public Zen::Vap::RootDelegate {
	float fps = 0;
	int nth = 0;
	// use shared_ptr pointer....
	weak_ptr<RootScene2d> m_s2d;
	weak_ptr<RootScene3d> m_s3d;
public:

	virtual void onLaunch(Zen::Size2 view_size) override
	{
		Zen::App::Get()->setMultiTouch(false);
		Zen::App::Get()->setFramesPerSecond(60);
		Zen::App::Get()->setRotatable(true);

		auto size = Zen::Vap::Activity::Get()->getRealViewSize();
		LogV("ScreenSize: %.2f %.2f", size.w, size.h);

		gConfig.size = size;

		this->loadSource();

		this->load2d();
		this->load3d();

	}
	void load2d()
	{
		auto scene = make_shared<Scene2d>();
		Activity::Get()->getRootNode()->addNode(scene);

		scene->setOrder(2);
		// scene->projectView(0, gConfig.size.h, gConfig.size.w, -gConfig.size.h);
		scene->projectView(0, 0, gConfig.size.w, gConfig.size.h);

		auto s2d = make_shared<RootScene2d>();
//		scene->addNode(s2d);
		s2d->addTo(scene);
		m_s2d = s2d;
	}

	void load3d()
	{
		auto scene = make_shared<Scene3d>();
		Activity::Get()->getRootNode()->addNode(scene);

		scene->setOrder(1);

		float aspect = gConfig.size.w / gConfig.size.h;
		auto m1 = Mat4MakePerspective(60 * (M_PI / 180.0f), aspect, 2, 100);
		scene->getCamera().setMatrix(m1, 0);

		auto s3d  = make_shared<RootScene3d>();
		s3d->addTo(scene);
		m_s3d = s3d;

	}
	void loadSource()
	{
		auto font_data = Zen::Utils::Get()->loadResource("res/ft.ttf");
		Zen::FontCache::Get()->cacheFont("funny font", Zen::Font::Create(font_data));

		gConfig.font_brush = Zen::FontBrush::Create(Zen::FontCache::Get()->getFont("funny font"), 64);
	}

	Ticker ticker;
	virtual void onUpdate() override
	{
		if(m_s2d.expired()) return;

		++nth;
		if(nth == 60)
		{
			fps = (float)nth/ToSeconds(ticker.tick());

			nth = 0;

			m_s2d.lock()->setFPS(fps);
		}
	}
	bool v = true;
	virtual void onTouchDown(AppTouch touch) override {
		v = !v;
		if(!m_s3d.expired()) m_s3d.lock()->setVisible(v);
		if(m_s2d.use_count()) m_s2d.lock()->setVisible(!v);
	}

	virtual void onTouchMove(AppTouch touch) override {}

};
